package cn.lijigou.shopping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.domain.Shop;
import cn.lijigou.shopping.domain.Website;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.service.ServerService;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import cn.lijigou.shopping.util.LoadImageAysnc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


/**
 * @author 黄明
 * 
 * @version 创建时间：2012-4-6 上午11:30:49 
 * 类说明  热门团购 tab页面
 */
public class BuySiteActivity extends Activity implements OnClickListener,OnItemClickListener {
	private ListView buysite_list;
	private List<Website> hotWebsite;
	private Listadapter adapter;
	private View footerView;
	MainTabActivity parentView;
	View load_one;
	View load_two;
	private String selectCity="";
	Map<String,Integer> iconMap=new HashMap<String,Integer>();
	String[] tuanString=new String[]{"窝窝团","拉手网","58团购","美团网","24券","F团","大众点评团","聚划算","糯米网","嘀嗒团","满座","千品","看购网"};
	Integer[] tuanIcon=new Integer[]{R.drawable.tuan_1,R.drawable.tuan_2,R.drawable.tuan_3,R.drawable.tuan_4,R.drawable.tuan_5,R.drawable.tuan_6,R.drawable.tuan_7,R.drawable.tuan_8,R.drawable.tuan_9,R.drawable.tuan_10,R.drawable.tuan_11,R.drawable.tuan_12,R.drawable.tuan_13,};
	
//	public static  List<List<Shop>> dataSource = new ArrayList<List<Shop>>();
//	public static boolean[] isload = {true,true,true,true};
//	public static int[] dataPage = {1,1,1,1};
//	public static int dataType=1;
//	public static  List<String> recordError=new ArrayList<String>();
	
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	public Handler waitHander = new Handler(){
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what==1){
				adapter.setDate(hotWebsite);
				adapter.notifyDataSetChanged();
			}else if(msg.what==101){
				load_one.setVisibility(View.VISIBLE);
				load_two.setVisibility(View.GONE);
			}else if(msg.what==102){
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.GONE);
			}else if(msg.what==103){
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.VISIBLE);
			}else if(msg.what==104){
				if(HomeActivity.dataSource.get(HomeActivity.dataType).size()==0){
					 Toast.makeText(BuySiteActivity.this,"亲,没有分类数据哦,请查看别的分类", 1).show(); 
				}else{
					 Toast.makeText(BuySiteActivity.this,"亲,已经是最后一条了哦", 1).show(); 
				}
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.GONE);
			}
		}
	};
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.buysite);
		initViews();
		getHotWebsite();
		 
	}
	
	TimerTask task = null;
	Timer timer = null;
	private void getHotWebsite() {
		// TODO Auto-generated method stub
		if(task==null){
			task = new TimerTask() { 
				public void run() { 
					if(MSystem.mLocation!=null){
						if(getNetConnectState(BuySiteActivity.this)){
				    		waitHander.sendEmptyMessage(101);
							if(getNetConnectState(BuySiteActivity.this)){
								timer.cancel();
								executorService.execute(new Thread() {
									public void run() {
										Boolean temp = false;
										MResult mResult = MSystem.getHotWebsite(hotWebsite);
										if (mResult != null) {
											if (mResult.isSuccess()) {
												waitHander.sendEmptyMessage(1);
												// temp=mResult.isPage();
												// if(!mResult.isPage()){
												waitHander.sendEmptyMessage(102);
												// if(hotWebsite.size()>8){
												// MainTabActivity.showHander.sendEmptyMessage(102);
												// }
												// }
											} else {
												waitHander.sendEmptyMessage(104);
											}
										} else {
											waitHander.sendEmptyMessage(103);
										}
									}
								});
							}else{
									waitHander.sendEmptyMessage(103);
							}	
						}
					}
				}
			};
		}
		
		if( timer==null){
			timer = new Timer(); 
			timer.schedule(task, 0,3000);
		} 
		
		
	}
	private void initViews() {
		// TODO Auto-generated method stub
		for(int i=0;i<tuanString.length;i++){
			iconMap.put(tuanString[i], tuanIcon[i]);
		}
		
		selectCity=MSystem.selectCity.trim();
		findViewById(R.id.titleRightView).setVisibility(View.GONE);
		parentView=(MainTabActivity)BuySiteActivity.this.getParent();
		buysite_list = (ListView)this.findViewById(R.id.buysite_list);
		hotWebsite =new ArrayList<Website>();
		footerView= LayoutInflater.from(this).inflate(R.layout.list_bottom_line, null);
		load_one=footerView.findViewById(R.id.load_one);
		load_two=footerView.findViewById(R.id.load_two);
		
		if(!HomeActivity.isload[HomeActivity.dataType]){
			load_one.setVisibility(View.GONE);
		}else{
			load_one.setVisibility(View.VISIBLE);
		}
		load_two.setVisibility(View.GONE);
		load_two.setOnClickListener(this);
		buysite_list.addFooterView(footerView);
		buysite_list.setOnItemClickListener(this);
		adapter = new Listadapter(this, hotWebsite, buysite_list);
		buysite_list.setAdapter(adapter);
		this.findViewById(R.id.titleLeftView).setVisibility(View.GONE);
		this.findViewById(R.id.title_btn_right).setVisibility(View.GONE);
		((TextView)this.findViewById(R.id.text_center)).setText("热门团站");
	}

	public class Listadapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private List<Website>  websiteList;
		private Boolean refresh=true;
		private ListView listView;
		private LoadImageAysnc loadImageAysnc;
		public  class ViewHolderShop {
			public TextView name;
			private TextView info;
			private ImageView image;
		}
		public Listadapter(Activity a,List<Website> websiteList,ListView listview) {
			this.mInflater = LayoutInflater.from(a);
			this.websiteList=websiteList;
			this.listView = listview;
			loadImageAysnc = new LoadImageAysnc(a);
		}

		public Listadapter() {
			// TODO Auto-generated constructor stub
		}

		public int getCount() {
//			return shopList.size();
			return websiteList.size();
		}

		public void setDate(List<Website> websiteList) {
			
			refresh=true;
			this.websiteList=websiteList;
		}
		
		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}
		ViewHolderShop holder = null;
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				holder = new ViewHolderShop();
				convertView = mInflater.inflate(R.layout.buysitelist_item, null);
				holder.info = (TextView) convertView.findViewById(R.id.info);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.image = (ImageView) convertView.findViewById(R.id.image);
				
				convertView.setTag(holder);
			} else {
				holder = (ViewHolderShop) convertView.getTag();
			}
			
			
			
			
			Website website=websiteList.get(position);
			String name = website.getName();
			holder.info.setText(website.getCount()+"");
			holder.name.setText(name);
			
			if(iconMap.containsKey(name.trim())){
				int image=iconMap.get(name.trim());
				holder.image.setVisibility(View.VISIBLE);
				holder.image.setBackgroundResource(image);
			}else{
				holder.image.setVisibility(View.GONE);
			}
			
			
			if(websiteList.size()>0){
	    		
//				holder.shop_image.setTag(id);
//				//开始异步加载数据
//				Drawable drawable = loadImageAysnc.loadImage(position,shopList.get(position).getId(), shopList.get(position).getPhoto_small(), "small.jpg",new ImageCallBack() {
//					
//					public void imageLoaded(Drawable drawable, int position) {
//						// TODO Auto-generated method stub
//						ImageView imageViewTag = (ImageView) listView.findViewWithTag(id);
//						if(imageViewTag != null) {
//							imageViewTag.setBackgroundDrawable(drawable);
//						}
//					}
//				} );
//				if(drawable == null) {
//					 holder.shop_image.setBackgroundResource(R.drawable.load_small);
//				} else {
//					 holder.shop_image.setBackgroundDrawable(drawable);
//				}
				
				
			}
			return convertView;
		}
	}
	
	public void onClick(View v) {
		// TODO Auto-generated method stub
		MSystem.pv+=1;
		switch (v.getId()) {
		case R.id.load_two:
			TimerTask task = null;
			Timer timer = null;
			getHotWebsite();
			break;

		default:
			break;
		}
	}
	
	
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	 
		if(!(selectCity.trim().equals(MSystem.selectCity.trim())))
		{
		 
			selectCity=MSystem.selectCity.trim();
			
			hotWebsite.clear();
			adapter.setDate(new ArrayList());
			adapter.notifyDataSetChanged();
			if( timer!=null){
				timer.cancel();
			}
			timer=null;
			task=null;
			getHotWebsite();
			
			
			
			
		}
		
		if(!TodayBuyActivity.isload[TodayBuyActivity.dataType]){
			load_one.setVisibility(View.GONE);
		}else{
			load_one.setVisibility(View.VISIBLE);
		}
		
	}
	
	
	
 	public static boolean getNetConnectState(Context context) {
		boolean netConnect = false;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (info.isConnected() || infoM.isConnected()) {
			netConnect = true;
		}
		return netConnect;
	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		MSystem.pv+=1;
		// TODO Auto-generated method stub
		if(hotWebsite.size()>0&&position<hotWebsite.size()){
			
			
			
			
			Intent intent=new Intent(BuySiteActivity.this, BuySiteSortListActivity.class);
			intent.putExtra("id", hotWebsite.get(position).getId());
			startActivity(intent);
		}
	
		
	}
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
//    		MSystem.exit(this);
    		if(parentView != null){
    			Animation animation=AnimationUtils.loadAnimation(BuySiteActivity.this,R.anim.home_push_rightout);
    			parentView.mHost.getCurrentView().startAnimation(animation);
        		parentView.mHost.setCurrentTab(0);	
    			parentView.main_tab_home.setChecked(true);
			    Animation animations=AnimationUtils.loadAnimation(BuySiteActivity.this,R.anim.home_push_rightin);
			    parentView.mHost.getCurrentView().startAnimation(animations);
    		}

		
    		return true;
	    }else{
	    	return super.onKeyDown(keyCode, event);
	    }
    }
}

